package history.study.array;

// 904. 水果成篮
public class LeetCode_904 {
    public static void main(String[] args) {
        totalFruit(new int[]{0,1,2,2});
    }
    public static int totalFruit(int[] tree) {
        int length = tree.length;
        if (length == 0) return 0;
        int left = 0, right = 1;
        int A = tree[0], B = tree[0];
        int ASum = 1, BSum = 0;
        int maxNum = Integer.MIN_VALUE;
        while (right < length) {
            if (tree[right] == A) {
                ASum++;
                right++;
                continue;
            } else if (tree[right] == B) {
                BSum++;
                right++;
                continue;
            } else if (A == B) {
                B = tree[right];
                BSum++;
                right++;
                continue;
            }
            maxNum = Math.max(maxNum, ASum+BSum);
            while (ASum>0 && BSum>0) {
                if (tree[left] == A) {
                    ASum--;
                    left++;
                    continue;
                } else {
                    BSum--;
                    left++;
                    continue;
                }
            }
            if (ASum == 0) {
                A = tree[right];
            } else {
                B = tree[right];
            }
        }
        maxNum = Math.max(maxNum, ASum+BSum);
        return maxNum == Integer.MIN_VALUE?0:maxNum;
    }
}
